package com.snk.kof.extra.quartz.registrar;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.Order;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.scheduling.SchedulingException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.util.ClassUtils;

/**
 * @author keshan
 * @date 2022-01-03 上午9:58
 */
@Slf4j
@Order(1)
public class QuartzCronScheduledRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        if (!(registry instanceof BeanFactory)) {
            throw new SchedulingException("registry未实现BeanFactory接口，无法转换成BeanFactory");
        }
        String jobClassName = importingClassMetadata.getClassName();
        Class jobClass = getJobClass(jobClassName);
        if (!QuartzJobBean.class.isAssignableFrom(jobClass)) {
            throw new SecurityException("Job Class " + jobClass.getName() + "没有继承QuartzJobBean类");
        }
        EnableQuartzCronScheduledRegistrar.addToAnnotationOnClasses(jobClass);
    }

    private Class getJobClass(String className) {
        try {
            return ClassUtils.forName(className, null);
        } catch (ClassNotFoundException e) {
            log.error("jobClass={}", e.getMessage(), e);
            throw new SchedulingException("jobClass == null");
        }
    }
}
